package work4.work3;

import Uti.ScannerUti;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.zip.GZIPInputStream;

public class QWeather {
    public QWeather() {
        doWork();
    }
    static void doWork() {
        while(true) {
            String key = "bf60e343ed1b4cf6b227a76f8b23d81e";
            System.out.println("请输入城市,n结束");
            String city = ScannerUti.getSting();
            if(city.equals("n"))break;
            //获取城市Id
            String getIdUrl = null;
            try {
                getIdUrl = "https://geoapi.qweather.com/v2/city/lookup?location=" + URLEncoder.encode(city, "UTF-8") + "&key=" + key;
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            String s = GetInf.get(getIdUrl);

            String code = (String) JSON.parseObject(s).get("code");
            if(code.equals("404")){
                System.out.println("输入有误，请重新输入");
                continue;
            }
            JSONArray location = (JSONArray) JSON.parseObject(s).get("location");
            //System.out.println(location);
            String Id = location.getJSONObject(0).getString("id");
            String cityName = location.getJSONObject(0).getString("name");
            //获取weather
            String getWeather = "https://devapi.qweather.com/v7/weather/now?location=" + Id + "&key=" + key;
            String inf = GetInf.get(getWeather);
            JSONObject weather = JSON.parseObject(inf);
            JSONObject now = (JSONObject) weather.get("now");
            System.out.println(cityName);
            String temp = (String) now.get("temp");
            System.out.println("温度：" + temp);
            String text = (String) now.get("text");
            System.out.println("天气：" + text);
        }
    }
}
